<?php
declare(strict_types=1);

namespace src;

use http\Exception\RuntimeException;
use ReflectionMethod;

class ControllerDispatcher
{
    protected $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function dispatch(Route $route, $controller, $method)
    {
        $parameters =  $this->resolveClassMethodDependencies($controller, $method);
        return $controller->{$method}(...array_values($parameters));
    }

    protected function resolveClassMethodDependencies($instance, $method)
    {
        if (! method_exists($instance, $method)) {
            throw new RuntimeException("控制器方法不存在: {$method}");
        }

        $reflector = new ReflectionMethod($instance, $method);
        $parameters = [];
        foreach ($reflector->getParameters() as $key => $parameter) {
            $class = $parameter->getClass();
            $name = $parameter->getName();
            if (empty($class)){
                if (!$parameter->getDefaultValue()){
                    throw new RuntimeException("$name 没有默认值");
                }
                $parameters[$name] = $parameter->getDefaultValue();
            }else{
                $parameters[$name] = $this->container->make($parameter->getClass()->name);
            }
        }
        return $parameters;
    }

}